<?php

class SettingsController extends Controller
{
	public $layout='//layouts/columnsetting';
	/**
	 * This function used for getting the data
	 * 
	 */
	private  function getAllData($from,$to,$table,$pageSize,$gotoPage)
	{
		switch($table)
		{
			case 'expensecategory':
				$command  = Yii::app()->db->createCommand("EXEC stp_GetAllExpenseCategory :from, :to,:number_row");
				$command->bindValue(':from', $from, PDO::PARAM_INT);
				$command->bindValue(':to', $to, PDO::PARAM_INT);
				
				$command->bindParam(':number_row', $numberRow, PDO::PARAM_INT|PDO::PARAM_INPUT_OUTPUT, 1);
				
				$records = $command->queryAll();
				return array(
				    'tableName'=>'expensecategory',
					'numberRow'=> $numberRow,
					'pageSize'=>$pageSize,
					'gotoPage'=>$gotoPage,
					'fromRecord'=>$from,
					'toRecord'=>$to,
				    'columns'=> array(
						'Id'=>'Id',
						'CategoryName'=>'Category Name',
						'Description'=>'Description',
						'Enable'=>'Enable'					
				
					),
					'records'=> $records
				);
				break;
		}
	}
	/**
	 * This function is used for loading the expense category
	 */
	public function actionLoadExpenseCategory()
	{
		$from= 0;
		$to =0;
		$pageSize =0;
		$gotoPage =0;
		if(isset($_POST['pageSize'])&&isset($_POST['gotoPage']) && $_POST['pageSize']!="" && $_POST['gotoPage']!="")
		{
			 $pageSize = $_POST['pageSize'];
			 $gotoPage = $_POST['gotoPage'];
			 $from = ($gotoPage - 1)*$gotoPage+1;
			 $to = $gotoPage*$gotoPage;
		}
		else if(!isset($_POST['pageSize'])&&!isset($_POST['gotoPage'])&&isset($_POST['loadDefault']) && $_POST['loadDefault']=='1')
		{
			$from = Yii::app()->params['defaultFrom'];
			$to = Yii::app()->params['defaultTo'];
			$pageSize = Yii::app()->params['defaultPageSize'];
			$gotoPage = Yii::app()->params['defaultGotoPage'];
		}
	    $expenseCategory = $this->getAllData($from, $to, 'expensecategory',$pageSize,$gotoPage);
	    $this->renderJSON($expenseCategory);
             
	}
	protected function renderJSON($data) {
		header('Content-type: application/json');
		echo CJSON::encode($data);

		foreach (Yii::app()->log->routes as $route) {
			if ($route instanceof CWebLogRoute) {
				$route -> enabled = false;
				// disable any weblogroutes
			}
		}
		Yii::app() -> end();
	}
	private function paddingHtml($from,$to,$numberRow,$recordPerPage,$goToPage)
	{
		$recordString ="";
		$recordString .='<div id ="form-pager" class="pager tablesorter-pager">
		<form id="category-pager-form">
	    <input id="categoryrecordnumber" type="hidden" value="'.$numberRow.'" />
		<img alt="First" class="first" src="'.Yii::app()->baseUrl.'/images/first.png">
		<img alt="Prev" class="prev" src="'.Yii::app()->baseUrl.'/images/prev.png">
		<span class="pagedisplay">'.$from.' to '.$to.' of '.$numberRow.' rows</span> <!-- this can be any element, including an input -->
		<img alt="Next" class="next disabled" src="'.Yii::app()->baseUrl.'/images/next.png">
		<img alt="Last" class="last disabled" src="'.Yii::app()->baseUrl.'/images/last.png">
		<select id="categorypagesize" title="Select page size" class="pagesize">';
		
		for($i=10;$i<50;$i+=10)
		{
			if($i==$_POST['categorypagesize'])
				$recordString .='<option value="'.$i.'" selected >'.$i.'</option>';
			else
				$recordString .='<option value="'.$i.'">'.$i.'</option>';
		}
		$recordString .='</select>';
		$recordString .='<select id ="categorygotoPage" title="Select page number" class="categorygotoPage">';
			for ($i=1; $i <= $numberRow/$recordPerPage +1; $i++)
				if($i== $goToPage)
					$recordString .='<option value="'.$i.'" selected >'.$i.'</option>';
				else {
					$recordString .='<option value="'.$i.'">'.$i.'</option>';
				}
		$recordString .='</select>';
		$recordString .='</form></div>';
		return $recordString;
	}
	public function actionIndex()
	{
		$userModel = new User;
		$expenseCategoryModel = new Expensecategory;
		$groupModel = new Group;
		$customerModel = new Customer;
		$currencyModel = new Currency;
		$exchangeRateModel = new ExchangeRate;
		$unitModel = new Unit;
		$unitConverModel = new Unitconvert;
		$departmentModel = new Department;
		$companyModel = new Company;

		$this->render('index',array(
			'userModel'=>$userModel,
			'expenseCategoryModel'=>$expenseCategoryModel,
			'groupModel' => $groupModel,
			'customerModel'=>$customerModel,
			'currencyModel'=>$currencyModel,
			'exchangeRateModel'=>$exchangeRateModel,
			'unitModel'=>$unitModel,
			'unitConvertModel'=>$unitConverModel,
			'departmentModel'=>$departmentModel,
			'companyModel'=>$companyModel,												
		));
		
	}
    
	/**
	 * This function is used for loading the department of company by ajax
	 */
	public function actionLoadDepartment()
	{
		$result = "";
	
		if(isset($_REQUEST['company']))
		{
			if($_REQUEST['company']!="")
			{
				$departments= Yii::app()->db->createCommand("EXEC stp_GetAllDepartmentsByCompanyId @CompanyId ='".$_REQUEST['company']."'")->queryAll();
				if(!empty($departments))
				{
					foreach ($departments as $department) 
					{
						$result.="<option value='".$department['DepartmentId']."'>".$department['DepartmentName']."</option>";
					}
				}
			}
			else {
				$result.= '<option value="">Select company first</option>';
			}
		}
		echo $result;
	}
	
   public function actionAccount()
   {
   	 $this->render('account');
   }
   public function actionPreference()
   {
   	 $currencies  = Yii::app()->db->createCommand("EXEC stp_GetAllActivedCurrencies")->queryAll();
     $units = Yii::app()->db->createCommand("EXEC stp_GetAllActivedUnits")->queryAll();
   	 $this->render('preference',array(
   	 'currencies'=>$currencies,
   	 'units'=>$units
   	 ));
   }
   /**
    * 
    *This function is used for changing password
    */
   public function actionChangePassword()
   {
   	 if(isset($_POST['userId']))
   	 {
   	 	 $errorMessage = "";
	   	 $userId = $_POST['userId'];
	   	 $oldPassword = md5(Yii::app()->user->salt.$_POST['oldPassword']);
	   	 if($oldPassword == Yii::app()->user->password)
	   	 {
		   	 $newPassword = md5(Yii::app()->user->salt.$_POST['password']);
		   	 $command  = Yii::app()->db->createCommand("EXEC stp_ChangePassword :userId, :oldPassword, :newPassword, :errorMessage");
			 $command->bindValue(':userId', $userId, PDO::PARAM_INT);
			 $command->bindValue(':oldPassword', $oldPassword, PDO::PARAM_STR);
			 $command->bindValue(':newPassword', $newPassword, PDO::PARAM_STR);
			 $command->bindParam(':errorMessage', $errorMessage, PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT, 1);
			 $command->execute();
	   	 }
	   	 else 
	   	 {
	   	 	$errorMessage = "Old password is incorrect";
	   	 }
	     echo $this->renderJSON(array("errorMessage"=>$errorMessage));
	    
	   	 
   	 }
   	 
   }
	// Uncomment the following methods and override them if needed
	/*
	public function filters()
	{
		// return the filter configuration for this controller, e.g.:
		return array(
			'inlineFilterName',
			array(
				'class'=>'path.to.FilterClass',
				'propertyName'=>'propertyValue',
			),
		);
	}

	public function actions()
	{
		// return external action classes, e.g.:
		return array(
			'action1'=>'path.to.ActionClass',
			'action2'=>array(
				'class'=>'path.to.AnotherActionClass',
				'propertyName'=>'propertyValue',
			),
		);
	}
	*/
   /**
    * 
    * Update Preference
    */
   public function actionUpdatePreference()
   {
   	 if(isset($_POST['default_currency']))
   	 {
   	 	 $currencyDefaultId = $_POST['default_currency'];
   	 	 $currencyCashConversion = $_POST['surchargeAmount'];
   	 	 $unitDistanceRatePerMile = $_POST['default_mileageRate'];
   	 	 $unitDistanceRatePerKilometer = $_POST['default_kmRate'];
   	 	 $unitDistanceDefaultUnitId =$_POST['default_distanceUnit'];
   	 	 $timeDefaultHourlyRate = $_POST['default_hourlyRate'];
   	 	 $userId = Yii::app()->user->id;
   	 	 $emailNotifications = isset($_POST['email_reminders']);
   	 	 $emailSendCopy = isset($_POST['email_onReportSubmitOrForward']);
   	 	 $emailOccasionalUpdate = isset($_POST['subscribed']);
   	 	 $command = Yii::app()->db->createCommand("EXEC stp_UpdatePreferences :CurrencyDefaultId,:CurrencyCashConversion,:UnitDistanceRatePerMile,:UnitDistanceRatePerKilometer,:UnitDistanceDefaultUnitId,:TimeDefaultHourlyRate,:UserId,:EmailNotifications,:EmailSendCopy,:EmailOccasionalUpdate");
		 $command->bindValue(':CurrencyDefaultId', $currencyDefaultId, PDO::PARAM_INT);
		 $command->bindValue(':CurrencyCashConversion', $currencyCashConversion, PDO::PARAM_STR);
		 $command->bindValue(':UnitDistanceRatePerMile', $unitDistanceRatePerMile, PDO::PARAM_STR);
		 $command->bindValue(':UnitDistanceRatePerKilometer', $unitDistanceRatePerKilometer, PDO::PARAM_STR);
		 $command->bindValue(':UnitDistanceDefaultUnitId', $unitDistanceDefaultUnitId, PDO::PARAM_INT);
		 $command->bindValue(':TimeDefaultHourlyRate', $timeDefaultHourlyRate, PDO::PARAM_STR); 
		 $command->bindValue(':UserId', $userId, PDO::PARAM_INT);
		 $command->bindValue(':EmailNotifications', $emailNotifications, PDO::PARAM_BOOL);
		 $command->bindValue(':EmailSendCopy', $emailSendCopy, PDO::PARAM_BOOL); 	
		 $command->bindValue(':EmailOccasionalUpdate', $emailOccasionalUpdate, PDO::PARAM_BOOL);
		 $command->execute();	 		 		    	 	
   	 }
   }
}